#!/usr/bin/env bash

# 配置
BASE_DIR="/opt"

# 脚本设置
TMP_DIR="$(rm -rf /tmp/env-install* && mktemp -d -t env-install.XXXXXXXXXX)"
LOG_FILE="${TMP_DIR}/env-install.log"
ERROR_INFO="\n\033[31mERROR Summary: \033[0m\n  "
ACCESS_INFO="\n\033[32mACCESS Summary: \033[0m\n  "
SCRIPT_PARAMETER="$*"
COMMAND_OUTPUT=""

######################################################################################################
# 通用函数
######################################################################################################
# 信号处理
function trap::info() {
  [[ ${#ERROR_INFO} -gt 37 ]] && echo -e "$ERROR_INFO"
  [[ ${#ACCESS_INFO} -gt 38 ]] && echo -e "$ACCESS_INFO"
  [ -f "$LOG_FILE" ] && echo -e "\n\n  See detailed log >>> cat $LOG_FILE \n\n"
  trap '' EXIT
  exit
}

# 错误日志
function log::error() {
  local item; item="[$(date +'%Y-%m-%dT%H:%M:%S.%N%z')]: \033[31mERROR:   \033[0m$*"
  ERROR_INFO="${ERROR_INFO}${item}\n  "
  echo -e "${item}" | tee -a "$LOG_FILE"
}

# 基础日志
function log::info() {
  printf "[%s]: \033[32mINFO:    \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" | tee -a "$LOG_FILE"
}

# 警告日志
function log::warning() {
  printf "[%s]: \033[33mWARNING: \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" | tee -a "$LOG_FILE"
}

# 访问信息
function log::access() {
  ACCESS_INFO="${ACCESS_INFO}$*\n  "
  printf "[%s]: \033[32mINFO:    \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" | tee -a "$LOG_FILE"
}

# 执行日志
function log::exec() {
  printf "[%s]: \033[34mEXEC:    \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" >> "$LOG_FILE"
}

# 检查返回码
function check::exit_code() {
  local code=${1:-}
  local app=${2:-}
  local desc=${3:-}
  local exit_script=${4:-}
  if [[ "${code}" == "0" ]]; then
    log::info "[${app}]" "${desc} succeeded."
  else
    log::error "[${app}]" "${desc} failed."
    [[ "$exit_script" == "exit" ]] && exit "$code"
  fi
}

# 重试
function utils::retry() {
  local retries=$1
  shift
  local count=0
  until eval "$*"; do
    exit=$?
    wait=$((2 ** count))
    count=$((count + 1))
    if [ "$count" -lt "$retries" ]; then
      echo "Retry $count/$retries exited $exit, retrying in $wait seconds..."
      sleep $wait
    else
      echo "Retry $count/$retries exited $exit, no more retries left."
      return $exit
    fi
  done
  return 0
}

# 转义引号
function utils::quote() {
  # shellcheck disable=SC2046
  if [ $(echo "$*" | tr -d "\n" | wc -c) -eq 0 ]; then
    echo "''"
  elif [ $(echo "$*" | tr -d "[a-z][A-Z][0-9]:,.=~_/\n-" | wc -c) -gt 0 ]; then
    printf "%s" "$*" | sed -e "1h;2,\$H;\$!d;g" -e "s/'/\'\"\'\"\'/g" | sed -e "1h;2,\$H;\$!d;g" -e "s/^/'/g" -e "s/$/'/g"
  else
    echo "$*"
  fi
}

# 检查命令是否存在
function check::command_exists() {
  local cmd=${1}
  local package=${2}
  if command -V "$cmd" > /dev/null 2>&1; then
    log::info "[check]" "$cmd command exists."
  else
    log::warning "[check]" "I require $cmd but it's not installed."
    log::warning "[check]" "install $package package."
    command::exec "127.0.0.1" "yum install -y ${package}"
    check::exit_code "$?" "check" "$package install" "exit"
  fi
}

# 执行命令
function command::exec() {
  local host=${1:-"127.0.0.1"}
  shift
  local command="$*"
  if [[ "${SUDO_TAG:-}" == "1" ]]; then
    sudo_options="sudo -H -n -u ${SUDO_USER}"
    if [[ "${SUDO_PASSWORD:-}" != "" ]]; then
       sudo_options="${sudo_options// -n/} -p \"\" -S <<< \"${SUDO_PASSWORD}\""
    fi
    command="$sudo_options bash -c $(utils::quote "$command")"
  fi
  command="$(utils::quote "$command")"
  if [[ "${host}" == "127.0.0.1" ]]; then
    # 本地执行
    log::exec "[command]" "bash -c $(printf "%s" "${command//${SUDO_PASSWORD:-}/zzzzzz}")"
    # shellcheck disable=SC2094
    COMMAND_OUTPUT=$(eval bash -c "${command}" 2>> "$LOG_FILE" | tee -a "$LOG_FILE")
    local status=$?
  else
    # 远程执行
    local ssh_cmd="ssh"
    if [[ "${SSH_PASSWORD}" != "" ]]; then
      ssh_cmd="sshpass -p \"${SSH_PASSWORD}\" ${ssh_cmd}"
    elif [[ "$SSH_PRIVATE_KEY" != "" ]]; then
      [ -f "${SSH_PRIVATE_KEY}" ] || { log::error "[exec]" "ssh private_key:${SSH_PRIVATE_KEY} not found."; exit 1; }
      ssh_cmd="${ssh_cmd} -i $SSH_PRIVATE_KEY"
    fi
    log::exec "[command]" "${ssh_cmd//${SSH_PASSWORD:-}/zzzzzz} ${SSH_OPTIONS} ${SSH_USER}@${host} -p ${SSH_PORT} bash -c $(printf "%s" "${command//${SUDO_PASSWORD:-}/zzzzzz}")"
    # shellcheck disable=SC2094
    COMMAND_OUTPUT=$(eval "${ssh_cmd} ${SSH_OPTIONS} ${SSH_USER}@${host} -p ${SSH_PORT}" bash -c '"${command}"' 2>> "$LOG_FILE" | tee -a "$LOG_FILE")
    local status=$?
  fi
  return $status
}

######################################################################################################
# 安装函数
######################################################################################################
BASE_DIR="/home/www/logs"
#URL="https://mirrors.huaweicloud.com/apache/tomcat/tomcat-10/v10.1.17/bin/apache-tomcat-10.1.17.tar.gz"
URL="https://d6.injdk.cn/oraclejdk/11/jdk-11.0.16.1_linux-x64_bin.tar.gz"

function download_file() {
  log::info "[test]" "下载文件..."
  local host="127.0.0.1"
  local tmp_download="tmp_download"
  local tmp_dir="tmp"
  command::exec "${host}" "
    cd ${BASE_DIR}/test
    rm -rf ./${tmp_download}
    mkdir ./${tmp_download}
    cd ./${tmp_download}
    # 下载文件，文件不存在就不会生成
    wget --timeout=10 --waitretry=3 --tries=5 --retry-connrefused --no-check-certificate ${URL}
    file_name=\`ls ./ | head -n 1\`
    if [ -z \$file_name ];then
        # 下载失败
        echo '下载失败=${URL}'
        cd ../
    else
        # 下载成功
        mkdir ./${tmp_dir}
        tar -zxvf \$file_name -C ./${tmp_dir}
        mv \$file_name ../\$file_name
        cd ./${tmp_dir}
        file_name=\`ls ./ | head -n 1\`
        mv \$file_name ../../\$file_name
        cd ../../
    fi
    rm -rf ./${tmp_download}
  "
}

function test() {
  local val_1="6.8.3 6.9.3 7.4.2 7.5.1"
  local val_2="3.8.6  3.6.3  3.5.4  3.3.9"
  for val in $val_1 $val_2
  do
    log::info "[test]" "[${val}]"
  done
}

######################################################################################################
# 主调用逻辑
######################################################################################################
trap trap::info 1 2 3 15 EXIT

# 开始
log::info "[start]" "bash $0 ${SCRIPT_PARAMETER}"
#download_file
test

# bash <(curl -s https://gitee.com/LiZhiW/helm-chart/raw/master/01shell/test/01test.sh) [cmd]
